package com.cq.base.retrofit

import android.accounts.NetworkErrorException
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import java.net.ConnectException
import java.net.UnknownHostException
import java.util.concurrent.TimeoutException

/**
 * 作者: CQ
 * 日期: 2021-03-26
 * 说明:
 */
abstract class BaseObserver<T> : Observer<T> {
    override fun onComplete() {
        onRequestEnd()
    }

    override fun onSubscribe(d: Disposable?) {
        onRequestStart()
    }

    override fun onNext(value: T) {
        if (value != null) {
            try {
                onSuccess(value)
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
        } else {
            onFailure(Throwable("服务器返回数据为空"), false)
        }
        onRequestEnd()
    }

    override fun onError(e: Throwable?) {
        try {
            if (e is ConnectException
                || e is TimeoutException
                || e is NetworkErrorException
                || e is UnknownHostException
            ) {
                onFailure(e, true)
            } else {
                onFailure(e, false)
            }
        } catch (e1: java.lang.Exception) {
            e1.printStackTrace()
        }
        onRequestEnd()
    }

    /**
     * 请求开始
     */
    protected open fun onRequestStart() {}

    /**
     * 请求结束
     */
    protected open fun onRequestEnd() {}

    /**
     * 返回成功
     *
     * @param t
     * @throws Exception
     */
    @Throws(Exception::class)
    protected abstract fun onSuccess(t: T)

    /**
     * 返回失败
     *
     * @param e
     * @param isNetWorkError 是否是网络错误
     * @throws Exception
     */
    @Throws(Exception::class)
    protected abstract fun onFailure(
        e: Throwable?,
        isNetWorkError: Boolean
    )
}